package com.jumi.microservice.controller.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jm.member.common.core.utils.DelFlag;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.jwt.constant.JwtAdminInfo;
import com.jm.member.common.redis.service.RedisService;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.domain.MessageTemplate;
import com.jumi.microservice.dto.reponse.GoldPromoterReviewReponse;
import com.jumi.microservice.dto.reponse.ListLevelDataNewReponse;
import com.jumi.microservice.dto.reponse.ListLevelDataReponse;
import com.jumi.microservice.dto.request.GoldPromoterReviewUpdateRequest;
import com.jumi.microservice.entity.*;
import com.jumi.microservice.enums.*;
import com.jumi.microservice.mq.SendMessageHandler;
import com.jumi.microservice.service.*;
import com.jumi.microservice.util.MessageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 店长,金牌推广商申请 前端控制器
 * </p>
 *
 * @author 要挑客户管理团队
 * @since 2020-08-31
 */
@RestController
@RequestMapping("/api/up")
@Api(value = "C-店长,金牌推广商申请", tags = {"C-店长,金牌推广商申请接口"})
public class JmLevelUpController {

    @Autowired
    IJmIdentityAuthenticationService IdentityService;

    @Autowired
    IJmGoldPromoterReviewService GoldPromoterService;

    @Autowired
    RedisService redisService;

    @Autowired
    IJmUserService userService;

    @Autowired
    IJmUserTeamService teamService;

    @Autowired
    IJmUserLevelConfigService configService;

    @Autowired
    IJmUserLevelChangeLogService userLevelChangeLogService;

    @Autowired
    IJmUserInviteService inviteService;

    @Resource
    SendMessageHandler sendMessageHandler;

    static final Logger logger = LoggerFactory.getLogger(JmLevelUpController.class);

    @PostMapping("/manager")
    @ApiOperation("店长、角色认证添加")
    @ApiImplicitParam(name = "image",value = "认证图片",required = true)
    public ResponseResult IdentityAuthentication(String image) {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);
//        if(byId.getIsIdentityAuthentication() == CommonEnum.是)
//            return ResponseResult.error("该角色已认证过,无需再认证");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("uid", uid);
        JmIdentityAuthentication identity = IdentityService.getOne(wrapper);

        if (ObjectUtil.isNotEmpty(identity)) {

            UpdateWrapper<JmIdentityAuthentication> updateWrapper = new UpdateWrapper<JmIdentityAuthentication>();


//            QueryWrapper wrapper1 = WrapperUtil.getWrapper(null, null);

            updateWrapper.set("remark", "");
            updateWrapper.set("image", image);
            updateWrapper.set("status", CheckStatus.待审核);
            updateWrapper.set("create_time",LocalDateTime.now());
            updateWrapper.set("remark","");

            updateWrapper.eq("uid", uid);


            return ResponseResult.success(IdentityService.update(updateWrapper));


        } else {

            JmIdentityAuthentication Identity = new JmIdentityAuthentication();

            Identity.setId(0);
            Identity.setUid(uid);
            Identity.setImage(image);
            Identity.setRemark("");
            Identity.setStatus(CheckStatus.待审核);

            return ResponseResult.success(IdentityService.save(Identity));
        }
    }


    @PostMapping("/codeCheck")
    @ApiOperation("金牌手机短信验证")
    public ResponseResult codeCheck(String code, String phone) {

        MessageUtil.checkCode(code, redisService, MessageType.金牌推广商验证.getValue() + phone);

        return ResponseResult.success();

    }

    @PostMapping("/gold")
    @ApiOperation("金牌推广商认证添加")
    public ResponseResult GoldPromoter(@Validated GoldPromoterReviewUpdateRequest request) {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);

//        MessageUtil.checkCode(request.getCode(), redisService, MessageType.金牌推广商验证.getValue() + request.getIdPhone());

        JmGoldPromoterReview gold = new JmGoldPromoterReview();
        BeanUtils.copyProperties(request, gold);
        gold.setMemberId(uid);
        gold.setAddTime(LocalDateTime.now());
        gold.setStatus(CheckStatus.待审核);
        gold.setAdminId(0L);
        gold.setMessage("");

        return ResponseResult.success(GoldPromoterService.saveOrUpdate(gold));

    }

    @PostMapping("/levelUp")
    @ApiOperation("升级")
    @Transactional
    public ResponseResult levelUp(Integer upLevel, Integer uid) {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id", uid);
        JmUser userInfo = userService.getOne(wrapper);



        if (ObjectUtil.isEmpty(userInfo)) {

            return ResponseResult.error("暂无数据！");

        } else {

            Boolean checkBool = this.checkUpLevelQualification(userInfo.getLevel().getValue(), upLevel, uid);

            if (!checkBool)return ResponseResult.error("请求异常,账号异常小老弟");

            //如果升级是金牌推广商, 不会将origin_level改为当前等级
            if (upLevel != 4) {

                userInfo.setOriginLevel(userInfo.getLevel());
            }
            userInfo.setLevel(Level.getLevelByValue(upLevel));
            userInfo.setLastLevelUpTime(LocalDateTime.now());
            if(upLevel==2)
                userInfo.setIsIdentityAuthentication(CommonEnum.是);
            UpdateWrapper<JmUserTeam> teamWrapper = new UpdateWrapper<JmUserTeam>();
            //团队表修改等级
            teamWrapper.set("level", upLevel);
            teamWrapper.eq("uid", uid);
            GradeEnum gradeEnum = upLevel < userInfo.getOriginLevel().getValue() ? GradeEnum.降级 : GradeEnum.升级;
            //更新用户等级日志
            Long adminId = ServletUtils.getLoginId();
            String adminName = ServletUtils.getLoginName();
            JmUserLevelChangeLog changeLog = new JmUserLevelChangeLog(uid, userInfo.getLevel(), Level.getLevelByValue(upLevel), userInfo.getInviterId(), gradeEnum, LevelChangeEnum.正常升级
                    , null, "目标达成,升级为"+Level.getLevelByValue(upLevel).getDesc(), adminId, adminName, DelFlag.normal, LocalDateTime.now(), LocalDateTime.now());
            userLevelChangeLogService.save(changeLog);
            //发送会员通知
            try {
                MessageTemplate template = sendMessageHandler.getMessageTemplate(MessageSendType.MEMBER_SELF.getValue());
                String level = Level.getLevelByValue(upLevel).getDesc();
                String appMessageContent = StrUtil.format(template.getSmtAppContent(),level);
                String stationMessageContent = StrUtil.format(template.getSmtMessageContent(),level);;
                sendMessageHandler.sendMessage(appMessageContent, stationMessageContent, uid, MessageSendType.MEMBER_SELF.getValue());
            } catch (Exception e) {
                logger.info("消息发送失败!");
            }
            //查询上级  向上级推送消息
            JmUserInvite invite = inviteService.getInviteByUid(uid);//获得上级信息
            if (ObjectUtil.isNotEmpty(invite)) {
                try {
                    MessageTemplate template = sendMessageHandler.getMessageTemplate(MessageSendType.MEMBER_DIRECT.getValue());
                    Map map = new HashMap();

                    String hidenPhone = userInfo.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                    map.put("name",hidenPhone);
                    map.put("level",Level.getLevelByValue(upLevel).getDesc());
                    String appMessageContent = StrUtil.format(template.getSmtAppContent(),map);
                    String stationMessageContent = StrUtil.format(template.getSmtMessageContent(),map);;
                    sendMessageHandler.sendMessage(appMessageContent, stationMessageContent, uid, MessageSendType.MEMBER_DIRECT.getValue());
                } catch (Exception e) {
                    logger.info("消息发送失败!");
                }
            }

            return ResponseResult.success(userService.updateById(userInfo) && teamService.update(teamWrapper));

        }

    }

    @PostMapping("/getIdentityProgress")
    @ApiOperation("店长活角色认证进度")
    public ResponseResult getIdentityProgress() {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("uid", uid);
        JmIdentityAuthentication identity = IdentityService.getOne(wrapper);

        if (ObjectUtil.isEmpty(identity)) {
            JmIdentityAuthentication aa = new JmIdentityAuthentication();

            aa.setStatus(CheckStatus.未申请);
            aa.setQunName("聚米轻奢团购群"+byId.getCode());

            return ResponseResult.success(aa);
        }

        identity.setQunName("聚米轻奢团购群"+byId.getCode());

        return ResponseResult.success(identity);

    }

    @PostMapping("/getLevelList")
    @ApiOperation("等级详情进度")
    public ResponseResult getLevelList() {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);
        JmUserLevelConfig obj = this.getLevelConfig(byId.getLevel().getValue() == 4 ? byId.getLevel().getValue() : byId.getLevel().getValue()+1 );

        switch (byId.getLevel().getValue()) {
            //团购用户
            case 1:
                return this.getIdentityProgress();
            //店长
            case 2:
                ListLevelDataReponse Level = GoldPromoterService.getListLevel(uid, LevelCondition.金牌新增时间.getValue());
                Level.setConditionSum(obj.getChildrenNum());
                Level.setLevel(com.jumi.microservice.enums.Level.goodManager.getValue());
                Level.setConditionSalas(obj.getSales());
                Level.setCount(Level.getYouxiuCount());

                return ResponseResult.success(Level);
            //优秀和金牌
            case 3:
            case 4:
                ListLevelDataReponse LevelYouxiu = GoldPromoterService.getListLevel(uid, LevelCondition.金牌新增时间.getValue());

                ListLevelDataNewReponse returnData = new ListLevelDataNewReponse();

                BeanUtils.copyProperties(LevelYouxiu,returnData);

                returnData.setConditionSum(obj.getChildrenNum());
                returnData.setLevel(com.jumi.microservice.enums.Level.gold.getValue());
                returnData.setConditionSalas(obj.getSales());
                returnData.setConditionSum2(obj.getAddNum());

                returnData.setCount(LevelYouxiu.getJinpaiCount());

                GoldPromoterReviewReponse goldlist = GoldPromoterService.getGoldInfoById(uid);

                returnData.setData(goldlist);

                return ResponseResult.success(returnData);


        }

        return ResponseResult.error("抱歉用户信息错误！");

    }

    public JmUserLevelConfig getLevelConfig (Integer level) {

        return configService.getById(level);

    }

    public Boolean checkUpLevelQualification(Integer atLevel, Integer upLevel, Integer uid) {

        //防止傻逼


        //  先看看是不是有沙雕跳级升 或者 有沙雕重复升
        if ((upLevel - atLevel) > 1 || (upLevel - atLevel) == 0)return false;

        // 再看看有没有沙雕不符合条件就硬上的

        // 先搞个小循环  都判断一下
        switch (upLevel) {
            //TM店长的力量
            case 2:

                //看看有没有 小伙子 投机取巧的
//                JmIdentityAuthentication identity = IdentityService.getById(uid);
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.in("uid", uid);
                JmIdentityAuthentication identity = IdentityService.getOne(wrapper);
                if (ObjectUtil.isEmpty(identity) || identity.getStatus() != CheckStatus.已通过)return false;

                break;

            //TM优秀店长的力量
            case 3:

                //先看看这伙计有没有达成目标
                JmUserLevelConfig obj = this.getLevelConfig(3);

                ListLevelDataReponse LevelYouxiu = GoldPromoterService.getListLevel(uid, LevelCondition.金牌新增时间.getValue());

                Boolean yeji3 = LevelYouxiu.getSales() == null ? false :LevelYouxiu.getSales().compareTo(obj.getSales()) >= 0 ;

                Boolean count13 = LevelYouxiu.getJinpaiCount() == null ? false : LevelYouxiu.getYouxiuCount() >= obj.getChildrenNum();

                if (!yeji3 || !count13)return false;

                break;

            //TM金牌的力量
            case 4:

                //先看看这伙计有没有达成目标
                JmUserLevelConfig obj4 = this.getLevelConfig(4);

                ListLevelDataReponse LevelYouxiu4 = GoldPromoterService.getListLevel(uid, LevelCondition.金牌新增时间.getValue());

                Boolean yeji = LevelYouxiu4.getSales() == null ? false :LevelYouxiu4.getSales().compareTo(obj4.getSales()) >= 0 ;

                Boolean count1 = LevelYouxiu4.getJinpaiCount() == null ? false : LevelYouxiu4.getJinpaiCount() >= obj4.getChildrenNum();

                Boolean count2 = LevelYouxiu4.getCount2()== null ? false : LevelYouxiu4.getCount2() >=  obj4.getAddNum();

                if (!yeji || !count1 || !count2)return false;

                //再看看这伙计有没有申请通过
                JmGoldPromoterReview gold = GoldPromoterService.getById(uid);

                if (ObjectUtil.isEmpty(gold) || gold.getStatus() != CheckStatus.已通过)return false;

                break;
            //TM 沙雕的力量
            default:
                return false;


        }

        //都没有问题 给你个true
        return true;

    }

    @Transactional
    public ResponseResult deleteInviter(Integer uid) {

        JmUser user = userService.getById(uid);

        Integer id = user.getId();
        Integer inviterId = user.getInviterId();
        Long loginId = ServletUtils.getLoginId();
        String loginName = ServletUtils.getLoginName();
        //查询邀请关系表
        JmUserInvite invite = inviteService.getInviteByUid(id);
        //查询团队表,获得我的上级记录
        List<JmUserTeam> mySupers = teamService.getMySupers(id);
        //查询团队表,获得我的下级
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("team_uid", id);
        wrapper.eq("is_del", CommonEnum.否);
        wrapper.select("uid");
        //我的下级用户id
        List list = teamService.listObjs(wrapper, (Function<Object, Object>) o -> Integer.valueOf(o.toString()));
        list.add(-1);
        //查询我的下级与我的上级之间的记录
        List<Integer> mySuperIds = mySupers.stream().map(JmUserTeam::getTeamUid).collect(Collectors.toList());
        mySuperIds.add(-1);
        wrapper = new QueryWrapper();
        wrapper.eq("is_del", CommonEnum.否);
        wrapper.in("uid", list);
        wrapper.in("team_uid", mySuperIds);
        List<JmUserTeam> list1 = teamService.list(wrapper);//我的下级与我的上级记录

        //所有的上下级关系
        List<JmUserTeam> allTeam = new ArrayList<>(mySupers.size() + list1.size());
        allTeam.addAll(mySupers);
        allTeam.addAll(list1);
        //清理
        if (ObjectUtil.isNotEmpty(invite)) {
            invite.setIsDel(CommonEnum.是);
            invite.setUpdateTime(LocalDateTime.now());
            inviteService.updateById(invite);
        }
        if (ObjectUtil.isNotEmpty(allTeam)) {
            allTeam.stream().forEach(s -> {
                s.setIsDel(CommonEnum.是);
                s.setUpdateTime(LocalDateTime.now());
                s.setAdminId(loginId);
                s.setAdminName(loginName);
            });
            teamService.updateBatchById(allTeam);
        }

        //清理redis的团队链关系
        String zSetKey = StrUtil.format("set_invite_id_{}", inviterId);
        redisService.remZset(zSetKey, id.toString());
        redisService.remMap("hash_member_invite",id.toString());

        //最后修改user表
        user.setInviterId(0);
        userService.updateById(user);

        return ResponseResult.success(true);
    }

}
